#include "recordwindow.h"

RecordsWindow::RecordsWindow(QWidget *parent)
    : QWidget(parent), model(new QStandardItemModel(this)), tableView(new QTableView(this)),
      weeklyAvgLabel(new QLineEdit(this)), monthlyAvgLabel(new QLineEdit(this))
{



    QLabel *weekLabel = new QLabel("周平均摄入量:", this);
    QLabel *monthLabel = new QLabel("月平均摄入量:", this);

    QHBoxLayout *weekLayout = new QHBoxLayout;
    QHBoxLayout *monthLayout = new QHBoxLayout;
    weekLayout->addWidget(weekLabel);
    weekLayout->addWidget(weeklyAvgLabel);
    monthLayout->addWidget(monthLabel);
    monthLayout->addWidget(monthlyAvgLabel);

    QVBoxLayout *layout = new QVBoxLayout(this);

    model->setHorizontalHeaderLabels({"时间", "咖啡因摄入量"});
    tableView->setModel(model);
    layout->addWidget(tableView);
    layout->addLayout(weekLayout);
    layout->addLayout(monthLayout);

    setLayout(layout);

    tableView->adjustSize();
    loadCheckinRecords();
    calculateAverages();
    adjustSize();
}
void RecordsWindow::loadCheckinRecords() {

    QDateTime now = QDateTime::currentDateTime();
    QString past30Days = now.addDays(-30).toString("yyyy-MM-dd HH:mm:ss");

    QSqlQuery query;
    query.prepare("SELECT timestamp, caffeine FROM record WHERE timestamp >= :startTime");
    query.bindValue(":startTime", past30Days);

    if (!query.exec()) {
        qDebug() << "Failed to retrieve records:" << query.lastError();
        return;
    }
    while (query.next()) {
        QList<QStandardItem*> items;
        QDateTime timestamp = QDateTime::fromString(query.value(0).toString(), "yyyy-MM-dd HH:mm:ss");
        double intake = query.value(1).toDouble();
        items.append(new QStandardItem(timestamp.toString("yyyy-MM-dd HH:mm:ss")));
        items.append(new QStandardItem(QString::number(intake)));
        model->appendRow(items);
    }
}
void RecordsWindow::calculateAverages() {
    QSqlQuery query;
    QDateTime now = QDateTime::currentDateTime();
    QString past7Days = now.addDays(-7).toString("yyyy-MM-dd HH:mm:ss");
    QString past30Days = now.addDays(-30).toString("yyyy-MM-dd HH:mm:ss");

    query.prepare("SELECT AVG(caffeine) FROM record WHERE timestamp >= :start7Days");
    query.bindValue(":start7Days", past7Days);

    if (query.exec() && query.next()) {
        double weeklyAvg = query.value(0).toDouble();
        weeklyAvgLabel->setText(QString("%1 mg").arg(weeklyAvg));
    }

    query.prepare("SELECT AVG(caffeine) FROM record WHERE timestamp >= :start30Days");
    query.bindValue(":start30Days", past30Days);

    if (query.exec() && query.next()) {
        double monthlyAvg = query.value(0).toDouble();
        monthlyAvgLabel->setText(QString("%1 mg").arg(monthlyAvg));
    }
}
